package com.lib.util;

import cn.hutool.core.bean.BeanUtil;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class ParamUtil {
    /**
     *
     * @param parameterMap
     * @param bean
     * @param excludeKeys   排除键数组（页面的checkbox框不需转换）
     */
    public static void toBean(Map<String ,String[]> parameterMap, Object bean, String[] excludeKeys)  {
        Map tempMap = new HashMap();
        Iterator entries = parameterMap.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(valueObj instanceof String[]){
                boolean b = false;
                for(String key : excludeKeys){
                    if( key.equals( ((String[])valueObj)[0] ) ){
                        b = true;
                        break;
                    }
                }
                if(b){
                    tempMap.put(name,valueObj);
                }else{
                    tempMap.put(name,((String[])valueObj)[0]);
                }
            }else{
                tempMap.put(name, valueObj);
            }
        }
        BeanUtil.copyProperties(tempMap, bean);
    }
    /**
     *
     * @param parameterMap
     * @param beanClass
     * @param excludeKeys   排除键数组（页面的checkbox框不需转换）
     */
    public static <T> T toBean(Map<String ,String[]> parameterMap, Class<T> beanClass,String[] excludeKeys)  {
        Map tempMap = new HashMap();
        Iterator entries = parameterMap.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(valueObj instanceof String[]){
                boolean b = false;
                if(excludeKeys!=null) {
                    for (String key : excludeKeys) {
                        if (key.equals(((String[]) valueObj)[0])) {
                            b = true;
                            break;
                        }
                    }
                }
                if(b){
                    tempMap.put(name,valueObj);
                }else{
                    tempMap.put(name,((String[])valueObj)[0]);
                }
            }else{
                tempMap.put(name, valueObj);
            }
        }
        return BeanUtil.copyProperties(tempMap, beanClass);
    }
    public static <T> T toBean(Map<String ,String[]> parameterMap, Class<T> beanClass){
        return toBean(parameterMap,beanClass,null);
    }

}
